// pages/autoplant/setting_page.js
var autoplant_public = require('autoplant_public.js');
var ble_master = require('../ble/ble_master.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    settingPageFloatingWindowEnable: false,
    settingPageIsGetInitialData: true,

    settingPageReceiveBoxDefaultValue: "Get Bluetooth messages here",
    settingPageSendBoxUserValue: "Send Bluetooth messages here",

    settingPageGettingBluetoothMsgTitle: "Got bluetooth data:",

    getPlantWet: autoplant_public.autoPlant_ble_value.getCMDHead + autoplant_public.autoPlant_ble_value.plantWet,
    plant1Num: autoplant_public.autoPlant_ble_value.plant1Num,
    plant2Num: autoplant_public.autoPlant_ble_value.plant2Num,
    getSystemBattery: autoplant_public.autoPlant_ble_value.getCMDHead + autoplant_public.autoPlant_ble_value.systemBattery,
    setSystemUTC: autoplant_public.autoPlant_ble_value.setCMDHead + autoplant_public.autoPlant_ble_value.systemUTC,
    splitChar: autoplant_public.autoPlant_ble_value.splitChar,
    getWaterWorkMode: autoplant_public.autoPlant_ble_value.getCMDHead + autoplant_public.autoPlant_ble_value.waterWorkModeCMD,
    getWorkingDayTime: autoplant_public.autoPlant_ble_value.getCMDHead + autoplant_public.autoPlant_ble_value.workingDayTime,
    getSingleWorkTime: autoplant_public.autoPlant_ble_value.getCMDHead + autoplant_public.autoPlant_ble_value.singleWorkTime,
    settingPageLastUpdateTime: "00:00:00",

    settingPageBLEConnectColor: "green",
    settingPageBLEDisonnectColor: "red",
    settingPageBLEConnecString: "Connected",
    settingPageBLEDisconnecString: "Disconnected",
    settingPageBLEConnectStateColor: "red",
    settingPageBLEConnectStateString: "Disconnected",

    settingPageWaterWorkModeSpecialTimeOnly: autoplant_public.autoPlant_ble_value.waterWorkModeSpecialTimeOnly,
    settingPageWaterWorkModeWithADC: autoplant_public.autoPlant_ble_value.waterWorkModeWithADC,
    settingPageWaterWorkMode: autoplant_public.autoPlant_ble_value.waterWorkModeSpecialTimeOnly,

    settingPageWaterWorkModes: ['仅使用特定浇水时长', '根据土壤湿度来确定浇水时长(Beta)'],

    settingPageMotor1Value: 0,
    settingPageMotor2Value: 0,

    settingPageDayTimeHourMinSecMultArry: [[], [], []],
    settingPageDayTimesSecs: [0],

    settingPageSingleWaterTimeSecs: [],
    settingPageDayTimeHourMinSecMultSelect: [0, 5, 3],
    settingPageSingleWaterTimeSecsPlant1: [0],
    settingPageSingleWaterTimeSecsPlant2: [0],
  },

  settingPageDayTimeHourMinSecMultArryInit: function() {
    var hour = []
    var minute = []
    var second = []

    for (let i = 0; i < 24; i++) {
      hour.push(i)
    }

    for (let i = 0; i < 60; i++) {
      minute.push(i)
      second.push(i)
    }

    var data = {
      multarry: this.data.settingPageDayTimeHourMinSecMultArry,
    }
    
    data.multarry[0] = hour
    data.multarry[1] = minute
    data.multarry[2] = second

    this.setData({
      settingPageDayTimeHourMinSecMultArry: data.multarry
    })
  },

  settingPageSingleWaterTimeSecsInit: function () {
    let secs = []
    for (let i = 0; i <= 120; i++) {
      secs.push(i)
    }
    this.setData({
      settingPageSingleWaterTimeSecs: secs
    })
  },

  settingPageShowInFloatingWindow: function(res) {
    // wx.showToast({
    //   title: res,
    //   // icon: 'loading',
    //   duration: 2500
    // })
    wx.showModal({
      title: this.data.settingPageGettingBluetoothMsgTitle,
      content: res,
    })
  },

  settingPageHandleSendBoxValue: function(res) {
    this.data.settingPageFloatingWindowEnable = false
    this.setData({
      settingPageSendBoxUserValue: res.detail.value
    })
  },

  settingPageGetButton: function(res) {
    // this.data.settingPageFloatingWindowEnable = true
    let cmd_value = res.target.id
    console.log(cmd_value)
    this.ble_sendData(ble_master.getCharsFromString(cmd_value))

    // this.settingPageShowInFloatingWindow(cmd_value)
  },

  settingPageUpdateUTC: function() {
    let update_utc_cmd = this.data.setSystemUTC + this.data.splitChar
    let utc_now = Math.round(new Date() / 1000)
    update_utc_cmd = update_utc_cmd + ble_master.getStringFromInt(utc_now)
    console.log(update_utc_cmd)
    this.ble_sendData(ble_master.getCharsFromString(update_utc_cmd))
  },

  settingPageSendData: function() {
    console.log(this.data.settingPageSendBoxUserValue)
    this.ble_sendData(ble_master.getCharsFromString(this.data.settingPageSendBoxUserValue))
  },

  motorRunForAWhile: function(e) {
    let motor_cmd = autoplant_public.autoPlant_ble_value.setCMDHead + autoplant_public.autoPlant_ble_value.motorPWM + e.target.id + this.data.splitChar + ble_master.getStringFromInt(100)
    console.log(motor_cmd)
    this.ble_sendData(ble_master.getCharsFromString(motor_cmd))
  },

  ble_handleReceivedData: function(head, value) {
    // console.log(head + ':' + value)
    let date = new Date()
    let time = date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds()
    this.setData({
      settingPageLastUpdateTime: time,
      // settingPageWaterWorkMode: value
    })

    let head_len = head.length
    if(head_len == 2) {
      // Water work mode
      if(head == autoplant_public.autoPlant_ble_value.waterWorkModeCMD) {
        this.setData({
          settingPageWaterWorkMode: value
        })
        if (this.data.settingPageIsGetInitialData == true) {

          if (this.data.settingPageIsGetInitialData == true) {
            // Get motor 1 pwm 
            let get_cmd = autoplant_public.autoPlant_ble_value.getCMDHead + autoplant_public.autoPlant_ble_value.motorPWM + autoplant_public.autoPlant_ble_value.plant1Num
            this.ble_sendData(ble_master.getCharsFromString(get_cmd))
          }
          
        } 
      }
    } else if (head_len == 3) {
      let head_cmd = head.substring(0, head_len - 1)
      let head_value = head[head_len - 1]

      // Motor pwm
      if (head_cmd == autoplant_public.autoPlant_ble_value.motorPWM) {
        if (head_value == this.data.plant1Num) {
          this.setData({
            settingPageMotor1Value: value
          })

          if (this.data.settingPageIsGetInitialData == true) {
            // Get motor 2 pwm 
            let get_cmd = autoplant_public.autoPlant_ble_value.getCMDHead + autoplant_public.autoPlant_ble_value.motorPWM + autoplant_public.autoPlant_ble_value.plant2Num
            this.ble_sendData(ble_master.getCharsFromString(get_cmd))
          }
          

        } else if (head_value == this.data.plant2Num) {
          this.setData({
            settingPageMotor2Value: value
          })

          if (this.data.settingPageIsGetInitialData == true) {
            // Get day time
            let get_cmd = this.data.getWorkingDayTime + '0'
            this.ble_sendData(ble_master.getCharsFromString(get_cmd))
          }
        }
        // Work day time
      } else if (head_cmd == autoplant_public.autoPlant_ble_value.workingDayTime) {
        if (head_value == '0') {
          console.log("day time num: " + head_value)
        }
        let split_str = value.split(this.data.splitChar)
        if(split_str.length == 2) {
          let int_value = parseInt(split_str[0])
          let char_value = parseInt(split_str[1])

          if (char_value == 1) {
            console.log("Day time is " + char_value)
          }
          this.setData({
            settingPageDayTimeHourMinSecMultSelect: ble_master.hmsInt2Arrary(int_value)
          })

        } else {
          console.log("Split data length error")
        }


        // plant 1 single water time
        if (this.data.settingPageIsGetInitialData == true) {
          let get_cmd = this.data.getSingleWorkTime + this.data.plant1Num
          this.ble_sendData(ble_master.getCharsFromString(get_cmd))
        }
        

      // Single water time
      } else if (head_cmd == autoplant_public.autoPlant_ble_value.singleWorkTime) {
        if (head_value == this.data.plant1Num) {
          var data = {
            array: this.data.settingPageSingleWaterTimeSecsPlant1,
          }
          data.array[0] = value

          this.setData({
            settingPageSingleWaterTimeSecsPlant1: data.array
          })

          if (this.data.settingPageIsGetInitialData == true) {
            // plant 2 single water time
            let get_cmd = this.data.getSingleWorkTime + this.data.plant2Num
            this.ble_sendData(ble_master.getCharsFromString(get_cmd))
          }
        } else if (head_value == this.data.plant2Num) {
          var data = {
            array: this.data.settingPageSingleWaterTimeSecsPlant2,
          }
          data.array[0] = value

          this.setData({
            settingPageSingleWaterTimeSecsPlant2: data.array,
            settingPageIsGetInitialData: false
          })
        }
      }
      
    }

  },

  ble_getNotifyDataCallback: function (res) {
    let str = ble_master.getStringFromBuffer(res)
    
    console.log("Get notify data: " + str)
    let split_str = str.split(this.data.splitChar)
    if (2 == split_str.length) {
      let cmd_head = split_str[0]
      let cmd_value = null

      if(split_str[1].length == 4) {
        cmd_value = ble_master.getIntFromString(split_str[1])
      } else {
        let split_str_int = ble_master.getIntFromString(split_str[1].substring(0, 4))
        let split_str_char = split_str[1][4]
        split_str_char = ble_master.getIntFromStringNew(split_str_char)
        cmd_value = split_str_int + this.data.splitChar + split_str_char
        console.log(cmd_value)
      }
      
      this.setData({
        settingPageReceiveBoxDefaultValue: cmd_head + this.data.splitChar + cmd_value
      })
      // console.log(cmd_head + " " + cmd_value)
      this.ble_handleReceivedData(cmd_head, cmd_value)
    } else {
      this.setData({
        settingPageReceiveBoxDefaultValue: str
      })
      console.log("Get wrong data")
    }
  },

  ble_turnOnNotifySuccessCallback: function () {
    console.log("Trun on notify success in callback function")
    ble_master.ble_getNotifyData(this.ble_getNotifyDataCallback)
    // this.mainPageInitCmdList()
    // this.initMainPageTimer()
    this.setData({
      settingPageIsGetInitialData: true
    })
    this.getSettingPageWaterWorkMode()
  },

  ble_connectSuccessCallback: function () {
    console.log("Connect to ble device " + ble_master.data.ble_device.deviceId + " success")
    this.setData({
      settingPageBLEConnectStateColor: this.data.settingPageBLEConnectColor,
      settingPageBLEConnectStateString: this.data.settingPageBLEConnecString
    })
    wx.showToast({
      title: 'Connected',
    })
    if (false == ble_master.data.isNotifyOn) {
      ble_master.ble_turnOnNotify(this.data.bleServiceUUID, this.data.bleCharUUID, this.ble_turnOnNotifySuccessCallback)
    } else {
      console.log("the is notify on state is " + ble_master.data.isNotifyOn)
      this.ble_turnOnNotifySuccessCallback()
    }


  },

  ble_init: function () {
    if (ble_master.data.ble_device) {
      if (!ble_master.data.isConnected) {
        this.setData({
          settingPageBLEConnectStateColor: this.data.settingPageBLEDisonnectColor,
          settingPageBLEConnectStateString: this.data.settingPageBLEDisconnecString
        })
        ble_master.ble_connectToDevice(this.ble_connectSuccessCallback)
      } else {
        // wx.showToast({
        //   title: "Bluetooth already connect",
        // })
        this.ble_connectSuccessCallback()
      }
    } else {
      wx.showModal({
        title: 'Error',
        content: "No bluetooth device found, please exit and try again",
      })
    }
    // this.mainPageInitCmdList()
    // this.initMainPageTimer()
  },

  ble_sendData: function (res) {
    if (ble_master.data.isConnected) {
      ble_master.ble_sendData(res)
    } else {
      console.log("ble device not connect")
    }
  },
  settingPageWorkDayTimeTap: function(e) {
    // console.log(e.target.id + " " + this.data.settingPageDayTimesSecs[e.target.id])
    let date = new Date()

    var a_data = {
      arrary: this.data.settingPageDayTimeHourMinSecMultSelect,
    }

    a_data.arrary[0] = date.getHours()
    a_data.arrary[1] = date.getMinutes()
    a_data.arrary[2] = date.getSeconds()
    this.setData({
      settingPageDayTimeHourMinSecMultSelect: a_data.arrary
    })
    console.log(this.data.settingPageDayTimeHourMinSecMultSelect)
  },

  settingPageWorkDayTimeChange: function(e) {
    if (e.detail.value[0] < 8) {
      var hour = e.detail.value[0] - 8 + 24
    } else {
      hour = e.detail.value[0] - 8
    }

    let set_time = hour * 3600 + e.detail.value[1] * 60 + e.detail.value[2]
    console.log(set_time)

    var data = {
      multarry: this.data.settingPageDayTimesSecs,
    }
    data.multarry[e.target.id] = set_time
    this.setData({
      settingPageDayTimesSecs: data.multarry
    })

    let set_day_time_cmd = autoplant_public.autoPlant_ble_value.setCMDHead + autoplant_public.autoPlant_ble_value.workingDayTime + e.target.id + this.data.splitChar + ble_master.getStringFromInt(set_time)
    console.log(set_day_time_cmd)
    this.ble_sendData(ble_master.getCharsFromString(set_day_time_cmd))
  },

  settingPageSingleWaterTimeChange: function(e) {
    let set_single_water_cmd = autoplant_public.autoPlant_ble_value.setCMDHead + autoplant_public.autoPlant_ble_value.singleWorkTime + e.target.id + this.data.splitChar + ble_master.getStringFromInt(e.detail.value)
    console.log(set_single_water_cmd)
    this.ble_sendData(ble_master.getCharsFromString(set_single_water_cmd))
  },

  settingPageWaterWorkModesChange: function(e) {
    let mode = parseInt(e.detail.value)
    mode += 1
    // console.log("Get value is " + mode)
    let mode_cmd = autoplant_public.autoPlant_ble_value.setCMDHead + autoplant_public.autoPlant_ble_value.waterWorkModeCMD + this.data.splitChar + ble_master.getStringFromInt(mode)
    console.log(mode_cmd)
    this.ble_sendData(ble_master.getCharsFromString(mode_cmd))
  },

  getSettingPageWaterWorkMode: function() {
    let mode_cmd = this.data.getWaterWorkMode
    console.log(mode_cmd)
    this.ble_sendData(ble_master.getCharsFromString(mode_cmd))
  },

  settingPageMotorPWMSlideChanging: function(e) {
    if(e.target.id == this.data.plant1Num) {
      this.setData({
        settingPageMotor1Value: e.detail.value
      })
    } else if(e.target.id == this.data.plant2Num) {
      this.setData({
        settingPageMotor2Value: e.detail.value
      })
    } 
  },
  settingPageMotorPWMSlideChange: function(e) {
    if (e.target.id == this.data.plant1Num) {
      this.setData({
        settingPageMotor1Value: e.detail.value
      })
    } else if (e.target.id == this.data.plant2Num) {
      this.setData({
        settingPageMotor2Value: e.detail.value
      })
    } 

    let motor_cmd = autoplant_public.autoPlant_ble_value.setCMDHead + autoplant_public.autoPlant_ble_value.motorPWM + e.target.id + this.data.splitChar + ble_master.getStringFromInt(e.detail.value)
    console.log(motor_cmd)
    this.ble_sendData(ble_master.getCharsFromString(motor_cmd))
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log("setting page loading")
    this.settingPageDayTimeHourMinSecMultArryInit()
    this.settingPageSingleWaterTimeSecsInit()
    // First get the water working mode
    // Check wether the ble device is connect
    if (ble_master.data.isConnected) {
      ble_master.ble_getNotifyData(this.ble_getNotifyDataCallback)
      this.setData({
        settingPageBLEConnectStateColor: this.data.settingPageBLEConnectColor,
        settingPageBLEConnectStateString: this.data.settingPageBLEConnecString
      })
      console.log("Conenct, get the water mode")

      this.setData({
        settingPageIsGetInitialData: true
      })
      this.getSettingPageWaterWorkMode()
    } else {
      // this.ble_init()
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    console.log("setting page show")
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    ble_master.ble_disconnect()
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    // Go to the upper page, do nothing
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})